use dta\Turnout_District_Level, clear 

sort year PR_district
drop _merge
merge year PR_district using dta\AlternativeMargin
drop if _merge==2 /* PR-districts not in sample */

gen d2127=0
replace d2127=1 if year==1921|year==1924|year==1927

egen avgC1=mean(C1), by(PR_district d2127)
egen avgC2=mean(C2), by(PR_district d2127)
egen avgmin_distance=mean(min_distance), by(PR_district d2127)
egen avgmin_distance1=mean(min_distance1), by(PR_district d2127)
egen avgmin_distance_iXv_i=mean(min_distance_iXv_i), by(PR_district d2127)
egen avgmin_distance1_iXv_i=mean(min_distance1_iXv_i), by(PR_district d2127)

gen Margin=SMD_margin_pre
gen Margin2=SMD_margin_pre^2

tab PR_district, gen(d_PR_district)

gen ch_margin=avgmin_distance1-Margin

*** Analysis with heteroscedasticity-robust standard errors

eststo clear
reg ch_turnout Margin if year==1921, robust
eststo
reg ch_turnout Margin Margin2 if year==1921, robust
eststo
reg ch_turnout Margin avgmin_distance1 if year==1921, robust
eststo
reg ch_turnout ch_margin if year==1921, robust
eststo
reg ch_turnout Margin d_PR_* if year==1921, robust nocons
eststo
esttab using tables\Table2_robustSE.tex, replace cells(b(fmt(3)) se(par fmt(3))) r2 nostar  ///
drop(d_PR*) nodepvars nomtitles prehead("\begin{tabular}{l*{@M}{rr}}" "\hline") posthead(\hline) postfoot("\hline" "\end{tabular}")  

*** Analysis with cluster-robust standard errors

eststo clear
reg ch_turnout Margin if year==1921, cluster(PR_district)
eststo
reg ch_turnout Margin Margin2 if year==1921, cluster(PR_district)
eststo
reg ch_turnout Margin avgmin_distance1 if year==1921, cluster(PR_district)
eststo
reg ch_turnout ch_margin if year==1921, cluster(PR_district)
eststo
reg ch_turnout Margin d_PR_* if year==1921, cluster(PR_district) nocons
eststo
esttab using tables\Table2_clusteredSE.tex, replace cells(b(fmt(3)) se(par fmt(3))) r2 nostar   ///
drop(d_PR*) nodepvars nomtitles prehead("\begin{tabular}{l*{@M}{rr}}" "\hline") posthead(\hline) postfoot("\hline" "\end{tabular}")  
